package com.xb.loan.usercenter.user.user.service.impl;

import com.xb.loan.log.exception.BizException;
import com.xb.loan.token.factory.TokenServerUtil;
import com.xb.loan.token.factory.TokenVersionEnum;
import com.xb.loan.token.factory.VerifyTokenHandler;
import com.xb.loan.usercenter.service.user.ITokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;

@Service("tokenService")
public class TokenServiceImpl implements ITokenService {

    private static Logger logger = LoggerFactory.getLogger(TokenServiceImpl.class);
    @Resource
    private VerifyTokenHandler verifyTokenHandler;

    @Override
    public String createUserToken(Long uid, String deviceId) throws BizException {

        logger.info("create user token,uid:{},deviceId:{}", uid, deviceId);

        int version = TokenVersionEnum.VERSION_1.getValue();
        String accessToken = null;

        int time = (int) ((System.currentTimeMillis()+verifyTokenHandler.ACCESS_TOKEN_EXPIRSED) / 1000);
        try {
            accessToken = TokenServerUtil.generatorToken(uid, version, time);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return accessToken;
    }


    @Override
    public boolean removeToken(String token, Long uid, String deviceId) {
//        //清token数据库
//        int row = userDeviceTokenDao.deleteUserDeviceTokenByUidAndDeviceId(uid, deviceId);
//        logger.debug("removerToken info:token:{},uid:{},deviceId:{},row:{}", token, uid, deviceId, row);
//        UserDeviceTokenDTO userDeviceTokenDTO;
//        if (row > 0) {
//            //清token缓存
//            String tokenUserInfoKey = buildTokenRedisUserInfoKeyStr(token, deviceId);
//            try {
//                //从缓存中读出用户信息，目前暂时只有uid
//                userDeviceTokenDTO = redisUtils.getSerialObject(tokenUserInfoKey, UserDeviceTokenDTO.class);
//                userDeviceTokenDTO.setIfLogin(false);//用户离线
//                redisUtils.setSerialObjectWithinSeconds(tokenUserInfoKey, userDeviceTokenDTO, CommonConstant.ACCESS_TOKEN_EXPIRSED);
//            } catch (Exception e) {
//                logger.error("offline token from redis error,uid:{},deviceId:{},error:{}", uid, deviceId, e);
//                return false;
//            }
//            return true;
//        }
        return false;
    }

    /**
     * weekVerifyToken的强弱校验
     *
     * @param token     member token
     * @param deviceId member deviceId
     * @return 校验结果
     * @throws Exception
     */
    @Override
    public Long weekVerifyToken(String token, String deviceId) throws BizException {
        logger.info("weekVerifyToken token:{},deviceId:{}", token, deviceId);
        if(org.apache.commons.lang3.StringUtils.isAnyEmpty(token,deviceId)){
            logger.error("weekVerifyToken token or deviceId is null");
            return 0L;
        }
        verifyTokenHandler = new VerifyTokenHandler();
        Long uid = verifyTokenHandler.weakVerifyToken(token, deviceId);

        return uid;
    }




    @Override
    public boolean isValidRefreshToken(String refreshToken) throws BizException {
        return false;
    }

    @Override
    public Date getTokenDate(String token) {
        return verifyTokenHandler.getDate(token);
    }

    @Override
    public long getTokenTime(String token) {
        try {
            Date  createDate = verifyTokenHandler.getDate(token);
            return createDate.getTime();
        } catch (Exception e) {
            logger.error("verify isValidAccessToken token expires error.{}", e);
            return 0;
        }
    }

    /**
     * 验证accessToken是否过期
     */
    @Override
    public boolean isValidAccessToken(String accessToken) {

        Date createDate;
        try {
            createDate = verifyTokenHandler.getDate(accessToken);
        } catch (Exception e) {
            logger.error("verify isValidAccessToken token expires error.{}", e);
            return false;
        }
        long createDateTime = createDate.getTime();
        long nowTime = new Date().getTime();
        return createDateTime + VerifyTokenHandler.ACCESS_TOKEN_EXPIRSED * 1000L > nowTime;

    }

    public static void main(String[] args) throws Exception {
        TokenServiceImpl tsi = new TokenServiceImpl();
        Long uid = 161108193305000067L;

        String token = tsi.createUserToken(uid,"13899101100");
        System.out.println("token = " + token);

        Long lo = tsi.weekVerifyToken(token,"13899101100");
        System.out.println("lo = " + lo);

    }

}
